package lowijs.XfireClient.packet;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.*;

import java.io.*;
import java.net.*;

public class FriendGamePacket extends Packet {
	private final String gamedataUrl = 
		"http://domnious.com/michiel/gamedata.php";
	
	private String gamename;
	private byte[] image;
	
	public FriendGamePacket(byte[] data) {
		int numSids = fromLowHigh(data[9], data[10]);
		Friend[] friends = new Friend[numSids];
		int pos = 11;

		FriendManager fm = FriendManager.getInstance();

		for (int i = 0; i < numSids; i++) {
			byte[] sid = new byte[16];
			System.arraycopy(data, pos, sid, 0, 16);
			friends[i] = fm.getFriendBySid(sid);
			pos += 16;
		}

		pos += 11; // jump to the gameids

		for (int i = 0; i < numSids; i++) {
			int gameid = Util.fromBytes(data, pos, 4);
			if (friends[i] != null) {
				if (gameid == 0)
					friends[i].setOutOfGame();
				else {
					getGamedataById(gameid);
					friends[i].setInGame(gamename, image);
				}
				EventManager.fireEvent(new FriendGameEvent(friends[i]));
			}
			pos += 4;
		}
	}
	
	private void getGamedataById(int gameid) {
		try {
			File file = new File(Util.STORAGE_PATH + "/" + gameid + ".dat");
			if (!file.exists()) {
				file.createNewFile();
				
				URL url = new URL(gamedataUrl + "?game=" + gameid);
				DataInputStream in =
					new DataInputStream(url.openStream());
				
				int nameLen = in.read(), imgLow = in.read(), imgHigh = in.read();
				int imgLen = 0 | imgLow | (imgHigh << 8);
				
				byte[] buffer = new byte[nameLen + imgLen];
				in.read(buffer, 0, buffer.length);
				in.close();
				
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(nameLen);
				fos.write(imgLow);
				fos.write(imgHigh);
				fos.write(buffer);
				fos.close();
			}

			FileInputStream fis = new FileInputStream(file);
			
			int nameLen = fis.read();
			int imgLen = 0 | fis.read() | (fis.read() << 8);
			
			byte[] gamenameBytes = new byte[nameLen];
			fis.read(gamenameBytes, 0, gamenameBytes.length);
			gamename = new String(gamenameBytes);
			
			image = new byte[imgLen];
			fis.read(image, 0, image.length);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
